﻿#region Usings...
using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using System.Windows.Forms;
#endregion

namespace MC_Launcher.Classes.Config
{
    /// <summary>
    /// 
    /// </summary>
    public class ConfigReadWrite
    {
        private Config _config;
        private static ConfigReadWrite _instance;

        private ConfigReadWrite()
        {
        }

        /// <summary>
        /// 
        /// </summary>
        public static ConfigReadWrite Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new ConfigReadWrite();
                }
                return _instance;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public Config CurrentConfig
        {
            get
            {
                try
                {
                    if (_config == null)
                    {
                        _config =
                            (Config)
                            new XmlSerializer(typeof(Config)).Deserialize(
                                new MemoryStream(File.ReadAllBytes("Profile.xml")));
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error parsing Profile XML: ", ex.Message.ToString());
                    _config = new Config();
                }
                return _config;
            }
        }

        /// <summary>
        /// Saves the current config back to the file
        /// </summary>
        /// <returns>true, if successful</returns>
        public bool SaveConfig()
        {
            if (_config == null) return false;
            try
            {
                XmlSerializer ser = new XmlSerializer(typeof(Config));
                MemoryStream ms = new MemoryStream();
                ser.Serialize(ms, _config);
                File.WriteAllText("Profile.xml", Encoding.UTF8.GetString(ms.GetBuffer()));
            }
            catch
            {
                return false;
            }
            return true;
        }
    }
}
